function writeCodeFile(fileManager, saveUrl, base64Data) {
	return new Promise((resolve, reject) => {
		fileManager.writeFile({
			filePath: '' + saveUrl,
			data: base64Data,
			encoding: 'base64',
			success(res1) {
				console.log('写入成功', res1);
				resolve()
			},
			fail(err1) {
				console.log(err1);
				uni.showToast({
					title: '写入图片失败',
					icon: 'none'
				});
				reject()
			}
		});
	})

}

function checkFileExit(fileManager, saveUrl) {
	return new Promise((resolve, reject) => {
		fileManager.access({
			path: '' + saveUrl,
			success() {
				resolve(true)
			},
			fail(err) {
				resolve(false)
			}
		});
	})
}

function saveFile(saveUrl) {
	wx.saveImageToPhotosAlbum({
		filePath: saveUrl,
		success: function(res) {
			wx.showToast({
				title: '保存成功'
			});
		},
		fail: function(err) {
			console.log(err);
		}
	});
}

export const saveImg = function(saveDir, saveUrl, base64Data) {
	let fileManager = wx.getFileSystemManager();
	//文件夹是否存在
	fileManager.access({
		path: `${wx.env.USER_DATA_PATH}/${saveDir}`,
		success(res1) {
			console.log(res1);
			//检查文件是否存在
			checkFileExit(fileManager, saveUrl).then(res => {
				if (res) { //存在，直接保存到本地
					saveFile(saveUrl)
				} else { //不存在，写入
					writeCodeFile(fileManager, saveUrl, base64Data).then(() => {
						saveFile(saveUrl)
					})
				}
			})
			// writeCodeFile(fileManager, saveUrl, base64Data);
		},
		fail(err1) {
			console.log(err1);
			fileManager.mkdir({
				dirPath: `${wx.env.USER_DATA_PATH}/${saveDir}`,
				success() {
					writeCodeFile(fileManager, saveUrl, base64Data).then(() => {
						saveFile(saveUrl)
					});
				},
				fail(err2) {
					console.log(err2);
					uni.showToast({
						title: '写入图片失败',
						icon: 'none'
					});
				}
			});
		}
	});
}
